package topcoder;

import java.util.StringTokenizer;

public class ThreeTeleports {

	private long dist(int x1, int y1, int x2, int y2){
		long sum = Math.abs(x1-x2) + Math.abs(y1-y2);
		return sum;
	}
	
	private long _shortestDistance(int x, int y, int hx, int hy, int[][] tel, long d, boolean[] used){
		if(x==hx && y==hy)
			return d;
		
		long min = d + dist(x,y,hx,hy);
		for(int i=0; i<3; i++){
			if(used[i]) continue;
			used[i] = true;
			
			long d1 = dist(tel[i][0],tel[i][1], x, y);
			long d2 = dist(tel[i][2],tel[i][3], x, y);
			long r1 = _shortestDistance(tel[i][2], tel[i][3], hx, hy, tel, d + 10 + d1, used);
			long r2 = _shortestDistance(tel[i][0], tel[i][1], hx, hy, tel, d + 10 + d2, used);
			
			if(Math.min(r1, r2) < min)
				min = Math.min(r1, r2);
			
			used[i] = false;
		}
		
		return min;
	}
	
	public int shortestDistance(int xMe, int yMe, int xHome, int yHome, String[] teleports){
		int[][] tel = new int[3][4];
		
		for(int i=0; i<3; i++){
			StringTokenizer tok = new StringTokenizer(teleports[i]);
			for(int j=0; j<4; j++)
				tel[i][j] = Integer.parseInt(tok.nextToken(" "));
		}
		
		return (int)_shortestDistance(xMe, yMe, xHome, yHome, tel, 0, new boolean[3]);
	}
	
	public static void main(String[] args) {
		ThreeTeleports t = new ThreeTeleports();
		t.shortestDistance(7, 2, 999999991, 4, new String[]{"0 1 0 999999999", "1 1000000000 999999999 0", "1000000000 1 1000000000 999999999"});
	}
}
